package com.yuyu.music.play.service.impl;

import com.yuyu.music.play.instance.PlayerInstance;
import com.yuyu.music.play.service.MusicPlayer;
import javazoom.jl.player.Player;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;

@Service
public class MusicPlayerImpl implements MusicPlayer {

    /**
     * 参考：Java 播放MP3
     * https://blog.csdn.net/qq_34814092/article/details/80889813
     *
     * @param musicInfo
     * @throws Exception
     */
    @Async
    @Override
    public void playMusic(String musicInfo) throws Exception {
        File file = new File("C:\\music\\" + musicInfo + ".mp3");
        FileInputStream stream = new FileInputStream(file);
        Player player = PlayerInstance.getPlayerInstance();
        if (player == null) {
            PlayerInstance.setPlayerInstance(stream);
            player = PlayerInstance.getPlayerInstance();
            player.play();
        } else {
            player.close();
            PlayerInstance.setPlayerInstance(stream);
            player = PlayerInstance.getPlayerInstance();
            player.play();
        }
    }

    @Override
    public void stopMusic() {
        Player player = PlayerInstance.getPlayerInstance();
        player.close();
    }
}
